<template>
  <div class="manual-correct">
    <div class="correct-container">
      <div class="question-panel">
        <div class="question-header">
          <span class="question-title">题目 {{ currentIndex + 1 }} / {{ totalQuestions }}</span>
          <span class="question-score">({{ currentQuestion.score }}分)</span>
        </div>

<!--        <div class="question-content" v-html="currentQuestion.content"></div>-->
        <formula-renderer class="question-content" :html="currentQuestion.content" />

        <div v-if="currentQuestion.options && currentQuestion.options.length" class="question-options">
          <h4>选项:</h4>
          <ul>
            <li
              v-for="option in currentQuestion.options"
              :key="option.id"
              :class="{
                'correct-option': option.isCorrect,
                'selected-option': isSelected(option.optionCode)
              }"
            >
<!--              {{ option.optionCode }}. <span v-html="option.content"></span>-->
              {{ option.optionCode }}.<formula-renderer :html="option.content" />

            </li>
          </ul>
        </div>

        <div v-if="currentQuestion.answers && currentQuestion.answers.length" class="question-answers">
          <h4>参考答案:</h4>
<!--          <div v-for="answer in currentQuestion.answers" :key="answer.id" v-html="answer.content">
              </div>-->
          <div v-for="answer in currentQuestion.answers" :key="answer.id" class="answer-item" >
            <formula-renderer v-html="answer.content" />
          </div>
        </div>
      </div>

      <div class="answer-panel">
        <h3>学生作答</h3>
        <div class="student-info">
          <span>{{ currentStudent.nickName }} ({{ currentStudent.userName }})</span>
        </div>

        <div v-if="currentAnswer.selectedOptionCodes" class="selected-options">
          <p>选择选项: {{ currentAnswer.selectedOptionCodes }}</p>
        </div>

<!--        <div v-if="currentAnswer.answerContent" class="answer-content" v-html="currentAnswer.answerContent"></div>-->
        <formula-renderer v-if="currentAnswer.answerContent" class="answer-content" v-html="currentAnswer.answerContent" />

        <div v-else class="empty-answer">
          <el-empty description="学生未作答" />
        </div>
      </div>

      <div class="correct-panel">
        <h3>批改</h3>

        <div class="score-input">
          <el-slider
            v-model="correctForm.score"
            :min="0"
            :max="currentQuestion.maxScore"
            :step="0.5"
            show-input
          >
          </el-slider>
          <span class="max-score">满分: {{ currentQuestion.maxScore }}</span>
        </div>

        <div class="comment-input">
          <el-input
            v-model="correctForm.comment"
            type="textarea"
            :rows="4"
            placeholder="请输入评语"
          ></el-input>
        </div>

        <div class="correct-tools">
          <el-button-group>
            <el-button
              type="primary"
              icon="el-icon-check"
              @click="handleCorrect(true)"
              :loading="loading"
            >
              保存并下一题
            </el-button>
            <el-button
              type="success"
              icon="el-icon-finished"
              @click="handleCorrect(false)"
              :loading="loading"
            >
              仅保存
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-close"
              @click="handleSkip"
              :disabled="loading"
            >
              跳过
            </el-button>
          </el-button-group>
        </div>
      </div>
    </div>

    <div class="navigation-buttons">
      <el-button
        type="info"
        plain
        :disabled="currentIndex <= 0"
        @click="prevQuestion"
      >
        上一题
      </el-button>
      <el-button
        type="info"
        plain
        :disabled="currentIndex >= totalQuestions - 1"
        @click="nextQuestion"
      >
        下一题
      </el-button>
    </div>
  </div>
</template>

<script>
import { getQuestionDetail, getTeacherAnswer, manualCorrect } from '@/api/exam/score'
import FormulaRenderer from "@/components/FormulaRenderer/index.vue";

export default {
  name: 'ManualCorrect',
  components: {FormulaRenderer},
  props: {
    recordId: {
      type: Number,
      required: true
    },
    questionId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      currentIndex: 0,
      totalQuestions: 0,
      questions: [],
      answers: [],
      students: [],
      currentQuestion: {
        id: null,
        content: '',
        options: [],
        answers: [],
        score: 0,
        maxScore: 0
      },
      currentAnswer: {
        id: null,
        selectedOptionCodes: null,
        answerContent: null
      },
      currentStudent: {
        id: null,
        userName: '',
        nickName: ''
      },
      correctForm: {
        score: 0,
        comment: ''
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    async initData() {
      try {
        this.loading = true

        // 根据传入参数决定是批改单个题目还是单个学生
        if (this.questionId) {
          // 获取该题目所有待批改的学生答案
          const res = await getTeacherAnswer({
            questionId: this.questionId,
            examId: this.$route.query.examId
          })
          this.answers = res.data.answers
          this.students = res.data.students
          this.totalQuestions = this.students.length

          // 获取题目详情
          const questionRes = await getQuestionDetail(this.questionId)
          this.currentQuestion = {
            ...questionRes.data,
            maxScore: questionRes.data.score
          }

          // 设置当前学生和答案
          if (this.answers.length > 0) {
            this.currentAnswer = this.answers[0]
            this.currentStudent = this.students[0]
            this.correctForm.score = this.currentAnswer.score || 0
            this.correctForm.comment = this.currentAnswer.correctComment || ''
          }
        } else {
          // 获取该学生所有待批改的题目
          const res = await getTeacherAnswer({
            recordId: this.recordId
          })
          this.questions = res.data.questions
          this.answers = res.data.answers
          this.totalQuestions = this.questions.length

          // 获取学生信息
          this.currentStudent = res.data.student

          // 设置当前题目和答案
          if (this.questions.length > 0) {
            this.currentQuestion = this.questions[0]
            this.currentAnswer = this.answers[0]
            this.correctForm.score = this.currentAnswer.score || 0
            this.correctForm.comment = this.currentAnswer.correctComment || ''
          }
        }
      } catch (error) {
        console.error('初始化批改数据失败:', error)
        this.$message.error('获取批改数据失败')
      } finally {
        this.loading = false
      }
    },

    isSelected(optionCode) {
      return this.currentAnswer.selectedOptionCodes &&
        this.currentAnswer.selectedOptionCodes.includes(optionCode)
    },

    async handleCorrect(goNext) {
      try {
        this.loading = true

        await manualCorrect({
          examId: this.$route.query.examId,
          recordId: this.recordId,
          answerId: this.currentAnswer.id,
          questionId: this.currentQuestion.id,
          score: this.correctForm.score,
          comment: this.correctForm.comment
        })

        this.$message.success('批改成功')

        if (goNext) {
          this.nextQuestion()
        }
      } catch (error) {
        console.error('批改失败:', error)
        this.$message.error('批改失败')
      } finally {
        this.loading = false
      }
    },

    handleSkip() {
      this.nextQuestion()
    },

    prevQuestion() {
      if (this.currentIndex > 0) {
        this.currentIndex--
        this.updateCurrentData()
      }
    },

    nextQuestion() {
      if (this.currentIndex < this.totalQuestions - 1) {
        this.currentIndex++
        this.updateCurrentData()
      } else {
        this.$emit('success')
        this.$message.success('已完成所有批改')
      }
    },

    updateCurrentData() {
      if (this.questionId) {
        // 按题目批改模式
        this.currentAnswer = this.answers[this.currentIndex]
        this.currentStudent = this.students[this.currentIndex]
      } else {
        // 按学生批改模式
        this.currentQuestion = this.questions[this.currentIndex]
        this.currentAnswer = this.answers[this.currentIndex]
      }

      // 重置表单
      this.correctForm.score = this.currentAnswer.score || 0
      this.correctForm.comment = this.currentAnswer.correctComment || ''
    }
  }
}
</script>

<style scoped>
.manual-correct {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.correct-container {
  display: flex;
  flex: 1;
  height: calc(100% - 60px);
  margin-bottom: 20px;
}

.question-panel {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  border-right: 1px solid #ebeef5;
}

.answer-panel {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  border-right: 1px solid #ebeef5;
}

.correct-panel {
  width: 300px;
  padding: 20px;
  overflow-y: auto;
}

.question-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.question-title {
  font-weight: bold;
  margin-right: 10px;
}

.question-score {
  color: #666;
}

.question-content {
  margin-bottom: 20px;
}

.question-options {
  margin: 20px 0;
}

.question-options ul {
  list-style: none;
  padding: 0;
}

.question-options li {
  padding: 8px;
  margin: 5px 0;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.correct-option {
  background-color: #f0f9eb;
  border-color: #e1f3d8 !important;
}

.selected-option {
  background-color: #f4f4f5;
}

.question-answers {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.student-info {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.selected-options {
  margin: 15px 0;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.answer-content {
  margin-top: 15px;
  padding: 15px;
  background-color: #ecf5ff;
  border-radius: 4px;
}

.empty-answer {
  margin-top: 20px;
}

.score-input {
  margin: 20px 0;
}

.max-score {
  display: block;
  text-align: right;
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.comment-input {
  margin: 20px 0;
}

.correct-tools {
  margin-top: 30px;
  text-align: center;
}

.navigation-buttons {
  text-align: center;
  padding: 10px 0;
  border-top: 1px solid #ebeef5;
}
</style>
